package com.thti.mecool.client.service;

import org.codehaus.jackson.map.ObjectMapper;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.threeti.mecool.core.domain.model.message.MobileMessage;
import com.thti.mecool.client.activity.R;
import com.thti.mecool.client.activity.UserCenterMsgListActivity;
import com.thti.mecool.client.model.biz.MessagesBizImpl;
import com.thti.mecool.client.model.po.MobileMessages;
import com.thti.mecool.client.util.Util;

/**
 * 
 * @author weiguo.ren
 * 
 */

public class NotificationReceiver extends BroadcastReceiver {
	static final String ACTION = "com.cn.android.NotificationService";
	static NotificationManager myNotiManager;
	MessagesBizImpl messagesBizImpl;
	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction().equals(ACTION)) {
			try { 
				String msg = intent.getStringExtra("msg");
				Util.print("msg:       " + msg);
				messagesBizImpl=new MessagesBizImpl(context);
				ObjectMapper mapper = new ObjectMapper();
				MobileMessage message=mapper.readValue(msg, MobileMessage.class);
				MobileMessages messages=new MobileMessages();
				messages.setId(String.valueOf(message.getId()));
				messages.setHead(message.getHead());
				messages.setBody(message.getBody());
				messages.setCreatedOn(String.valueOf(message.getCreatedOn()));
				messages.setPriority(message.getPriority().name());
				messages.setType("UNREAD");
				myNotiManager = (NotificationManager) context
						.getSystemService("notification");
				Long time = message.getCreatedOn();
				messagesBizImpl.save(messages);
				CharSequence contentTitle =messages.getHead();
				CharSequence contentText = messages.getBody();
				Util.print("contentTitle:       " + contentTitle);
				Util.print("contentText:       " + contentText);
				Intent notifyIntent = new Intent(context, UserCenterMsgListActivity.class);
				notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

				Notification myNoti = new Notification(R.drawable.ic_launcher,
						"Notification", time);
				Util.print("time:       " + time);
				myNoti.setLatestEventInfo(context, contentTitle, contentText,
						PendingIntent.getActivity(context, 0, notifyIntent, 0));
				myNoti.flags |= Notification.FLAG_AUTO_CANCEL;
				myNoti.defaults |= Notification.DEFAULT_SOUND;
				myNotiManager.notify(0, myNoti);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}

	}

}
